/*
 * @description:
 * @version: 1.0.1
 * @Author: xuqiulin
 * @Date: 2021-04-30 11:08:50
 * @LastEditors:
 * @LastEditTime: 2021-04-30 21:29:39
 */
package controllers

import (
	"GameServer/Common/utils"
	"GameServer/Game/player"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

type Serv struct {
	Ip        string `json:"ip"`
	Port      string `json:"port"`
	BeginTime string `json:"beginTime"`
	EndTime   string `json:"endTime"`
}

var tMainten *time.Timer = nil

// 通知服务器维护
func NoticeMaintenance(c *gin.Context) {
	// 如果定时器已经设置，需要停掉，重新设置
	if tMainten != nil {
		tMainten.Stop()
		tMainten = nil
	}

	var serv Serv
	if err := c.ShouldBindJSON(&serv); err != nil {
		handleErr(c, err.Error())
		return
	}
	log.Infof("系统维护 %+v\n", serv)
	bTime, _ := strconv.ParseInt(serv.BeginTime, 10, 64)
	eTime, _ := strconv.ParseInt(serv.EndTime, 10, 64)
	nTime := utils.TNow().Unix()
	log.Info("现在时间 ", utils.TNow())
	log.Info("维护起始时间 ", utils.TTime(bTime, 0))
	log.Info("bTime ", bTime)
	log.Info("eTime ", eTime)
	log.Info("nTime ", nTime)
	log.Info(time.Duration(bTime-nTime) * time.Second)

	if bTime-nTime <= 0 {
		handleErr(c, "维护起始时间-现在时间<=0")
		return
	}

	tMainten = time.AfterFunc(time.Duration(bTime-nTime)*time.Second, func() {
		log.Info("现在时间", utils.TimeToLayout(utils.TNow()))
		log.Info("开始踢人 bTime", bTime, "eTime", eTime)
		tlist := player.GetOnlinePlayers()
		for _, item := range tlist {
			log.Info(item.User.Uid.Hex(), item.User.Name)
			item.NoticeMainen(bTime, eTime)
		}
		log.Info("踢人结束")
	})

	mdata := make(map[string]interface{}, 0)
	mdata["msg"] = "通知完成"
	handleOk(c, mdata)
}
